package com.wx.registerclient.config;



import com.wx.registerclient.entity.ServerInfomation;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.nd4j.shade.jackson.databind.ObjectMapper;




import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;



import java.io.IOException;
import java.io.InputStream;

/**
 * http远程调用
 * 获得服务对应的ip地址与端口号
 */
@Configuration
public class HttpClientConfig  {




    public ServerInfomation getObject(String serverName,String host,String port)  {

        CloseableHttpClient build = HttpClientBuilder.create().build();

        // TODO 解决注册中心地址与端口号硬编码
        String url="http://"+host+":"+port+"/register/getInfo/"+serverName;
        HttpGet httpGet = new HttpGet(url);

        // 配置信息
        RequestConfig requestConfig = RequestConfig.custom()
                // 设置连接超时时间(单位毫秒)
                .setConnectTimeout(2000)
                // 设置请求超时时间(单位毫秒)
                .setConnectionRequestTimeout(2000)
                // socket读写超时时间(单位毫秒)
                .setSocketTimeout(2000)
                // 设置是否允许重定向(默认为true)
                .setRedirectsEnabled(true).build();
        // 将上面的配置信息 运用到这个Get请求里
        httpGet.setConfig(requestConfig);
        // 请求参数


        // 发送4请求
        try {
            CloseableHttpResponse execute = build.execute(httpGet);
            // 获取响应的实体
            HttpEntity entity = execute.getEntity();
            // 获得输入流
            InputStream content = entity.getContent();
            // 读取json字符串
            StringBuffer stringBuffer = new StringBuffer();
            int j=0;
            byte[] bytes = new byte[1024];

            while ((j=content.read(bytes))!=-1){
                String string = new String(bytes,0,j);
                stringBuffer.append(string);
            }
            // 把json字符串转换为对象
            String json = stringBuffer.toString();

            ServerInfomation serverInfomation = new ObjectMapper().readValue(json, ServerInfomation.class);

            return serverInfomation;

        } catch (IOException e) {
            return null;
        }


    }
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}
